<template>
	<div>
		<use-table ref="tbl" :tableRefs="$refs.etbl"></use-table>
		<div class="container_status dflex_vertical_c">
			<div class="item_interval" v-for="(item, i) in stateDatas" :key="i">
				<el-button class="badge_txt" :class="{ active: item.name == state }" size="small" @click="cutSta(item)">
					<span v-if="item.name == '处理中'">待处理</span>
					<span v-else>{{item.name}}</span>
				</el-button>
				<v-countup class="badge" start-value="0" :end-value="item.cnt"></v-countup>
			</div>
		</div>
		<div class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">订单号：</div>
					<el-input v-model="req.order_id" type="number" placeholder="请输入" class="search_input"
						@change="search" clearable></el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">用户名称：</div>
					<el-input v-model="req.member_name" placeholder="请输入" class="search_input" @change="search"
						clearable></el-input>
				</div>
				<div class="dflex_vertical_c margin_r_40 margin_b_20" v-if="advancedSearch">
					<div class="search_name">申请时间：</div>
					<el-date-picker v-model="searchTime" type="daterange" align="right" range-separator="至"
						start-placeholder="开始日期" end-placeholder="结束日期" format="yyyy-MM-dd"
						:picker-options="pickerTimeOptions" class="search_start_end_time" @change="search">
					</el-date-picker>
				</div>
				<el-button size="mini" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40"
					@click="search">搜索</el-button>
				<div class="search_advanced margin_b_20" @click="advancedSearch = !advancedSearch"
					v-if="!advancedSearch">高级筛选</div>
				<div class="search_common margin_b_20" @click="advancedSearch = !advancedSearch" v-if="advancedSearch">
					常用筛选</div>
			</div>
		</div>
		<div class="container last_container use-table">
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas" highlight-current-row
				@sort-change="sortable">
					<!-- <el-table-column label="订单号" align="center" min-width="200">
						<template scope="scope">
							<div class="theme_color crpr" @click="toOrderDetail(scope.row.order_id[0].order_id)">
								{{ scope.row.order_id[0].order_id }}
							</div>
						</template>
					</el-table-column>
					<el-table-column label="用户" align="center" min-width="190">
						<template slot-scope="scope">
							<div class="dflex_vertical_c">
								<el-image class="headimg_small"
									:src="scope.row.member_headimg || 'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'"
									:preview-src-list="scope.row.previewImgs" fit="contain"></el-image>
								<div class="margin_l_5 ellipsis_2 left_just">{{ scope.row.member_name }}</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="订单金额" align="center" min-width="120">
						<template scope="scope">
							<div class="price">
								{{ scope.row.refund_money / 100 || "--" }}
							</div>
						</template>
					</el-table-column>
					<el-table-column property="goods_state" label="货物状态" align="center" min-width="100"></el-table-column>
					<el-table-column property="goods_state" label="货物状态" align="center" min-width="100"></el-table-column>
					<el-table-column property="reason" label="退款原因" align="center" min-width="140"></el-table-column>
					<el-table-column label="退款说明" align="center" min-width="180">
						<template slot-scope="scope">
							<div>{{ scope.row.desc || '--' }}</div>
						</template>
					</el-table-column>
					<el-table-column label="退款凭证" align="center" min-width="150">
						<template slot-scope="scope">
							<div class="dflex_level_c">
								<use-carousel v-if="scope.row.imgs.length > 0" :width="80" :height="80"
									:imgs="scope.row.imgs">
								</use-carousel>
							</div>
						</template>
					</el-table-column>
					<el-table-column label="商品" align="center" min-width="360">
						<template slot-scope="scope">
							<div class="dflex_vertical_c">
								<use-carousel :width="80" :height="80" :img="scope.row.order_id[0].goods_img"
									:imgs="scope.row.order_id[0].goods_imgs" :video="scope.row.order_id[0].goods_video">
								</use-carousel>
								<div class="left_just margin_l_10">
									<el-popover popper-class="use_popover" :open-delay="200" :close-delay="40"
										placement="right" :title="scope.row.order_id[0].goods_name" trigger="hover"
										:content="scope.row.order_id[0].goods_name_pw || '--'">
										<div slot="reference" class="dflex_d_c">
											<div class="ellipsis crpr">{{ scope.row.order_id[0].goods_name }}</div>
											<div class="ellipsis crpr">{{ scope.row.order_id[0].goods_name_pw || '--' }}
											</div>
										</div>
									</el-popover>
								</div>
							</div>
						</template>
					</el-table-column>
					<el-table-column property="remark" label="备注" align="center" min-width="100"></el-table-column>
					<el-table-column property="state" label="状态" align="center" min-width="100"></el-table-column>
					<el-table-column property="create_time" sortable="custom" label="申请时间" align="center" min-width="180">
					</el-table-column>
					<el-table-column label="操作" align="center" fixed="right" min-width="150">
						<template slot-scope="scope">
							<el-tooltip v-if="scope.row.state == '处理中'" :open-delay="350" content="同意退款" placement="top"
								:hide-after="1000" :enterable="false" effect="light">
								<el-button circle size="medium" icon="el-icon-check" class="table-btn"
									@click="consent(scope.row)"></el-button>
							</el-tooltip>
							<el-tooltip v-if="scope.row.state == '处理中'" :open-delay="350" content="拒绝退款" placement="top"
								:hide-after="1000" :enterable="false" effect="light">
								<el-button circle size="medium" icon="el-icon-close" class="table-btn"
									@click="refuse(scope.row)"></el-button>
							</el-tooltip>
							<el-tooltip :open-delay="350" content="详情" placement="top" :hide-after="1000" :enterable="false"
								effect="light">
								<el-button circle size="medium" icon="el-icon-more-outline" class="table-btn"
									@click="toOrderDetail(scope.row.order_id[0].order_id)"></el-button>
							</el-tooltip>
						</template>
					</el-table-column> -->
				<div slot="empty">
					<el-empty description=" "></el-empty>
				</div>
			</el-table>
			<el-pagination background :current-page="req.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="req.rows"
				layout="total, sizes, prev, pager, next, jumper" :total="tableTotal" @size-change="sizeChange"
				@current-change="currentChange"></el-pagination>
		</div>
		<el-drawer :title="form.lable" size="500px" :visible.sync="drawer" :wrapperClosable="false" direction="rtl"
			:append-to-body="true" @open="drawerOpen">
			<div class="dflex_c dflex_d_c margin_b_20">
				<el-image class="headimg"
					:src="refundsDisposeRow.member_headimg || 'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'"
					:preview-src-list="refundsDisposeRow.previewImgs" fit="contain"></el-image>
				<div class="margin_t_10">{{ refundsDisposeRow.member_name || '--' }}</div>
			</div>
			<el-form class="add_edit" :model="form" :rules="rules" ref="ruleForm" label-width="100px">
				<el-form-item v-show="form.lable == '同意退款'" label="订单金额">
					<el-input :value="refundsDisposeRow.refund_money / 100" disabled>
					</el-input>
				</el-form-item>
				<el-form-item v-show="form.lable == '同意退款'" label="退款金额" prop="rebate" ref="rebate">
					<el-input :disabled="refundsDisposeLoading" type="number" v-model="form.rebate" :min="0"
						placeholder="请输入退款金额" clearable>
					</el-input>
				</el-form-item>
				<el-form-item v-show="form.lable == '拒绝退款'" label="拒绝原因" prop="content" ref="content">
					<el-input type="textarea" placeholder="请输入拒绝原因" :autosize="{ minRows: 3 }" v-model="form.content">
					</el-input>
				</el-form-item>
				<el-form-item>
					<el-button :loading="refundsDisposeLoading" round icon="el-icon-check" class="confirm-btn"
						@click="submitForm('ruleForm')">提交</el-button>
					<el-button :disabled="refundsDisposeLoading" round icon="el-icon-back" class="return-btn"
						@click="drawer = false">返回</el-button>
				</el-form-item>
			</el-form>
		</el-drawer>
	</div>
</template>

<script>
	import vCountup from 'vue-countupjs';
	const __name = 'wmzmall-order-refund,wmzmall-order-detail';
	export default {
		components: {
			vCountup
		},
		data() {
			const validateRebate = async (rule, value, callback) => {
				if (this.form.lable == '同意退款') {
					if (!value) {
						return callback(new Error('请输入退款金额'));
					}

					if (value < 0) {
						return callback(new Error('请输入正确退款金额'));
					}

					if (value < 0.01) {
						return callback(new Error('退款金额不能小于0.01'));
					}

					if (value > (this.refundsDisposeRow.refund_money / 100)) {
						callback(new Error('退款金额不能大于订单金额'));
						return;
					}
				}

				callback();
			};
			const validateContent = async (rule, value, callback) => {
				if (this.form.lable == '拒绝退款') {
					if (!value) {
						return callback(new Error('请输入拒绝原因'));
					}
				}

				callback();
			};
			return {
				state: '全部',
				stateObj: {
					处理中: 0,
					待买家处理: 0,
					待卖家处理: 0,
					已拒绝: 0,
					已完成: 0,
					全部: 0
				},
				stateDatas: [],
				advancedSearch: false,
				searchTime: [],
				req: {
					page: 1,
					rows: 10,
					orderby: 'create_time desc',
					order_id: '',
					member_name: '',
					begin_time: '',
					end_time: ''
				},
				pickerTimeOptions: {
					disabledDate(time) {
						return time.getTime() > Date.now();
					},
					shortcuts: [{
							text: '最近一周',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
								picker.$emit('pick', [start, end]);
							}
						},
						{
							text: '最近一个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
								picker.$emit('pick', [start, end]);
							}
						},
						{
							text: '最近三个月',
							onClick(picker) {
								const end = new Date();
								const start = new Date();
								start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
								picker.$emit('pick', [start, end]);
							}
						}
					]
				},
				refundsDisposeRow: {},
				drawer: false,
				refundsDisposeLoading: false,
				form: {
					rebate: '',
					content: ''
				},
				rules: {
					rebate: [{
						required: true,
						validator: validateRebate,
						trigger: 'change'
					}],
					content: [{
						required: true,
						validator: validateContent,
						trigger: 'change'
					}]
				},
				tblHeight: 0,
				tableLoading: false,
				tableDatas: [],
				tableTotal: 0,
				searchBtnLoading: false
			};
		},
		methods: {
			async loadData(callback) {
				// this.tableLoading = true;

				this.stateDatas = [];
				for (let key in this.stateObj) {
					this.stateDatas.push({
						name: key,
						cnt: this.stateObj[key]
					});
				}

				this.req.begin_time = '';
				this.req.end_time = '';

				if (this.searchTime && this.searchTime.length > 0) {
					this.req.begin_time = this.searchTime[0].getTime();
					this.req.end_time = this.searchTime[1].getTime() + (60 * 60 * 24 - 1) * 1000;
				}
				
				return;

				await this.$db[__name]
					.whereif(this.req.state && this.req.state != '全部', {
						state: this.req.state
					})
					.whereif(this.req.member_name, {
						member_name: new RegExp(this.$api.filterRegexpKey(this.req.member_name), 'i')
					})
					.whereif(this.req.order_id, {
						'order_id.order_id': new RegExp(this.$api.filterRegexpKey(this.req.order_id), 'i')
					})
					.whereif(this.searchTime && this.searchTime.length > 0, {
						create_time: this.$db.$cmd.gte(this.req.begin_time).and(this.$db.$cmd.lte(this.req
							.end_time))
					})
					.withgroup({
						field: 'state',
						obj: this.stateObj
					})
					.totable(this.req)
					.then(res => {
						if (res.code == 200) {
							if (res.datas.group && res.datas.group.datas) {
								this.stateDatas = res.datas.group.datas;
							}

							res.datas.rows.forEach((row, idx) => {
								row.previewImgs = [(row.member_headimg && row.member_headimg.replace(
										"/132",
										"/0")) ||
									'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'
								];
								row.create_time = new Date(row.create_time).format();
							});

							this.tableDatas = res.datas.rows;
							this.tableTotal = res.datas.total;

							if (typeof callback === 'function') {
								callback();
							}
						}
						this.searchBtnLoading = false;
						this.tableLoading = false;
					});
			},
			search() {
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.searchBtnLoading = true;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});

				uni.setStorage({
					key: '__search' + this.$route.path,
					data: this.req
				});
			},
			sortable(column) {
				if (column.order) {
					column.order = column.order.replace('ending', '');
				}
				this.req.orderby = column.prop + ' ' + (column.order || 'desc');

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			toOrderDetail(order_id) {
				uni.navigateTo({
					url: `/pages/order/order/detail?order_id=${order_id}&flag=refunds_dispose&tab=订单详情`,
					events: {
						refreshData: () => {
							this.loadData();
						}
					}
				});
			},
			consent(row) {
				this.refundsDisposeRow = row;
				this.drawer = true;
				this.form.lable = '同意退款';
				this.form.rebate = row.refund_money / 100;
			},
			refuse(row) {
				this.refundsDisposeRow = row;
				this.drawer = true;
				this.form.lable = '拒绝退款';
				this.form.content = '';
			},
			drawerOpen() {
				if (this.$refs.ruleForm) {
					this.$refs.ruleForm.clearValidate();
				}
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.refundsDisposeLoading = true;

						this.$func.wmzadmin.call(this.form.lable == '同意退款' ? 'order/refund' : 'order/refuse', {
							id: this.refundsDisposeRow._id,
							order_id: this.refundsDisposeRow.order_id[0].order_id,
							rebate: this.form.lable == '同意退款' ? this.form.rebate : '',
							remark: this.form.lable == '同意退款' ? '退款成功' : this.form.content,
							state: this.form.lable == '同意退款' ? '已退款' : '拒绝退款'
						}, false).then(res => {
							if (res.code == 200) {
								this.$message({
									type: 'success',
									message: '操作成功!'
								});
								this.drawer = false;
								this.loadData();
							} else {
								this.$message({
									type: 'error',
									message: res.datas.message
								});
							}
							this.refundsDisposeLoading = false;
						});
					}
				});
			},
			cutSta(item) {
				uni.setStorage({
					key: '__cutSta' + this.$route.path,
					data: item
				});

				this.state = item.name;
				this.req.state = item.name;
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			sizeChange(size) {
				this.$api.storagePaginationRows(size, this.$route.path);
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.req.rows = size;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			currentChange(current) {
				this.$api.storagePaginationPage(current, this.$route.path);
				this.req.page = current;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			}
		},
		created() {
			let __search = uni.getStorageSync('__search' + this.$route.path);
			if (__search) {
				this.req = __search;
				if (this.req.member_name) {
					this.advancedSearch = true;
				}
				if (this.req.begin_time && this.req.end_time) {
					this.searchTime.push(new Date(this.req.begin_time), new Date(this.req.end_time));
					this.advancedSearch = true;
				}
			}

			let thisCutSta = uni.getStorageSync('__cutSta' + this.$route.path);
			this.state = '全部';
			this.req.page = 1;
			this.req.state = this.state;
			if (thisCutSta) {
				this.state = thisCutSta.name;
				this.req.state = thisCutSta.name;
			}

			this.req.page = uni.getStorageSync('__paginationPage' + this.$route.path) || 1;
			this.req.rows = uni.getStorageSync('__paginationRows' + this.$route.path) || 10;

			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.el-table__body-wrapper', this.$route.path);
				});
			});
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-table__body-wrapper', this.$route.path);
			});
		},
		updated() {
			if (!this.tblHeight) {
				this.tblHeight = this.$refs.tbl.tblHeight;
			}
		}
	};
</script>

<style>
	.theme_color:hover {
		text-decoration: underline;
	}

	.add_edit .el-input,
	.add_edit .el-textarea {
		width: 90%;
	}

	.ellipsis_2 {
		max-width: 100px;
	}

	>>>.el-drawer__header {
		margin-bottom: 20px;
	}
</style>
